package chixing.day18.homework.work4;

import java.util.concurrent.ArrayBlockingQueue;

public class PCP {
    /*
    * 缓冲队列
    * */
    private final  ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(10);

    /*
    * 生产者
    * */
    class Producer implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    blockingQueue.put(i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    /*
    * 消费者
    * */
    class Consumer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                blockingQueue.take();//阻塞队列直到队列为非空
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Producer getProducer(){
        return new Producer();
    }

    public Consumer getConsumer(){
        return new Consumer();
    }

    public static void main(String[] args) {
        PCP pcp = new PCP();
        new Thread(pcp.getProducer()).start();
        new Thread(pcp.getConsumer()).start();
    }
}
